<?php
/**
 * 俱乐部大赢家次数、总牌局次数
 * Created by PhpStorm.
 * Keter
 * 2016/8/1
 * @守护进程
 */
class PaijuClubActivityTopHandler extends ScriptBase
{
    /**
     * 游戏服保存的牌局日志KEY
     */
    const LOG_NAME = 'finalGame';

    /**
     * 出错备份
     */
    const QUEEN_BACKUP_NAME = 'finalGameBackup';

    /**
     * 俱乐部活动KEY
     */
    const ACTIVITY_NAME = 'clubActivity';


    /**
     * 当前脚本暂停标志
     * 同类结果为TRUE时则暂停和停止，如1
     */
    const SUSPEND_TAG = 'PAIJU_LOG_HANDLER_SUSPEND'; //暂停


    /**
     * 读取数据处理条数  add by tmac
     */
    const CACHE_LIMIT_NUMBER = 1000;

    /**
     * 日志文件大小  add by tmac
     */
    const LOG_FILE_SIZE = 254000000;
    /**
     * 过期时间
     */
    private $_expireTime;

    /**
     * 牌局日志Redis
     */
    protected $paijuRedis;

    /**
     * 逻辑代码
     */
    public function logic()
    {
        set_time_limit(0);

        $this->setExpireTime();
        //$this->addTest();

        while (true) {
            try {
                // 连接redis
                $this->paijuRedis = $this->redis('paiju_log');


                //暂停脚本循环
                if ($this->paijuRedis->get(self::SUSPEND_TAG)) {
                    continue;
                }

                //执行脚本
                //获取列表长度，来取条数
                $lenth = $this->paijuRedis->lLen( self::LOG_NAME );
                if( empty($lenth) ){
                    $this->deinitRedis('paiju_log');
                    sleep(1);
                    continue;
                }
                $lenth = $lenth <= self::CACHE_LIMIT_NUMBER ? $lenth : self::CACHE_LIMIT_NUMBER;
                for($i=0; $i<= $lenth; $i++ ){
                    $lastElement =  $this->paijuRedis->rpop(self::LOG_NAME);
                    $result = $lastElement ?  $this->logHandler($lastElement) : true;
                    // 如果没有处理成功，则放入备份队列
                    if ( !$result ) {
                        $this->paijuRedis->lpush(self::QUEEN_BACKUP_NAME, $lastElement);
                    }
                }
                //---end add

                // 断开redis
                $this->deinitRedis('paiju_log');
                usleep(10000);
            } catch (Exception $e) {
                //--add by tmac 2016-12-20
                $this->deinitRedis('paiju_log');
                sleep(1);
                //--end add
                $this->e($e->getMessage());
            }
        }
    }

    /**
     * 设置过期时间
     */
    public function setExpireTime()
    {
        if (isset(GlobalConfig::$redis_expire['paiju_log'])
            && GlobalConfig::$redis_expire['paiju_log']
        ) {
            $expireDay = (integer)GlobalConfig::$redis_expire['paiju_log'];
        } else {
            $expireDay = 5;
        }

        $this->_expireTime = 86400 * $expireDay;
    }

    /**
     * 执行脚本
     * @param $redis
     */
    public function logHandler($result )
    {
        //$this->paijuRedis->lpush(self::QUEEN_BACKUP_NAME, $result);
        if ($result) {
            is_array($result) && $result = reset($result); //  by tmac
            $str = $result;
            if  ($str) {
                $data = json_decode($str, true);
                //isset($data['clubID'])
                if(isset($data['clubID'])) {
                    $activity = $this->paijuRedis->hGetAll(self::ACTIVITY_NAME . ':' . $data['clubID']);
                    if ($activity) {
                        $time=time();
                        foreach ($activity as $k => $v) {
                            $json_v = json_decode($v, true);
                            //业务处理
                            if(($json_v['start_time']<=$time) &&  ($json_v['end_time']>=$time) &&  ($json_v['status']==1)){
                                $key_head='CLUBTOP:'.$data['clubID'].':'.$k.':';
                                if($json_v['sort']==2){//1参与桌数累计，2大赢家累计
                                    $user_score=[];
                                    foreach ($data['detail']['score'] as $k=>$v){
                                        $user_score[$k]=$v[1];
                                    }
                                    $max=max($user_score);
                                    $userlist=[];
                                    foreach ($data['detail']['score'] as $k=>$v){
                                        if($max==$v[1] && $max>0){
                                            $userlist[]=$data['uids'][$k];
                                        }
                                    }
                                    foreach ($userlist as $k=>$v){
                                        $re_key=$key_head.$v;
                                        $this->paijuRedis->incr($re_key);
                                    }
                                }else{
                                    foreach ($data['uids'] as $ku=>$vu){
                                        $re_key=$key_head.$vu;
                                        $this->paijuRedis->incrBy($re_key,$data['seq']);
                                    }
                                }
                             }
                        }
                    }
                }
            }
            return true;
        }
    }


    /**
     * 写入牌局数据库
     * @param $data
     */
    public function backup2db($data)
    {
        $data['uids'] = json_decode($data['uids'], JSON_UNESCAPED_UNICODE);
        $data['detail'] = json_decode($data['detail'], JSON_UNESCAPED_UNICODE);

        $paijuLog = new PaijuLog();
        $paijuLog->isRedisLog(false);
        $paijuLog->setTableName();

        /**
         * 保存牌局
         */
        $juData = $paijuLog->savePaijuLog($data);
        /**
         * 保存牌组
         */
        //---add by tmac 2016-12-20 修复 返回错误bug
        $result = count( $juData ) < 1 ? [] : $paijuLog->savePaizuInfo($data, $juData);
        count( $result ) < 1  && $result =  false;
        //---end add
       //$result = $paijuLog->savePaizuInfo($data, $juData);  //注释 by tmac 2016-12-20

        return $result;
    }

}
?>
